import React, { Fragment, useState } from 'react';
import { Button, Icon, Modal } from 'antd';
// import { formatMessage } from 'umi';
import UploadOss from '@/components/UploadOss';
// import styles from './index.less';

function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

const FileUpload = React.forwardRef(
    (
        {
            value = {},
            onChange,
            categoryCode = 'workflowFile',
            checkFileSize = 100,
            checkFileSizeMsg = '文件大小不能超过100MB！',
            checkFileType = 'JPG,JPEG,BMP,GIF,PNG,DOC,DOCX,ppt,pptx,PDF,xls,xlsx,RAR,ZIP,txt,ai',
            checkFileTypeMsg = '只能上传JPG,JPEG,BMP,GIF,PNG,DOC,DOCX,ppt,pptx,PDF,xls,xlsx,RAR,ZIP,txt,ai格式的文件！',
            isSingle = false,
            maxFileCount,
            ...rest
        },
        ref
    ) => {
        const [previewVisible, setPreviewVisible] = useState(false);
        const [previewImage, setPreviewImage] = useState('');
        // const { allFileList = [], uploadResourceFile } = value;
        const { allFileList = [] } = value;
        const changeAllFileList = (showFileList, uploadResource) => {
            // // 遍历文件状态，如果有正在上传或报错则改变mystatus为false，当点击提交时禁止提交
            // showFileList.forEach(item => {
            //     if (item.status === 'uploading' || item.status === 'error') {
            //         this.setState({
            //             mystatus: false
            //         });
            //     } else {
            //         this.setState({
            //             mystatus: true
            //         });
            //     }
            // });
            onChange({
                allFileList: showFileList,
                uploadResourceFile: uploadResource
            });
        };
        const handleImgPreview = async file => {
            if (!file.url && !file.preview) {
                file.preview = await getBase64(file.originFileObj);
            }
            setPreviewImage(file.url || file.preview);
            setPreviewVisible(true);
        };
        const uploadButton = (
            <div>
                <Icon type="plus" style={{ fontSize: 24, color: 'rgba(0, 0, 0, 0.45)' }} />
                <div>上传照片</div>
            </div>
        );
        // 三元表达式修改
        const fetchSingle = single => {
            if (single) {
                return allFileList.length >= 1 ? null : uploadButton;
            }
            return (
                <Button type="primary" ghost>
                    <Icon type="upload" />
                    上传文件
                </Button>
            );
        };

        // 用于新增多文件上传时，文件个数限制
        const childrenWithProps = React.Children.map(rest.children, child => {
            if (React.isValidElement(child)) {
                return React.cloneElement(child, { disabled: allFileList.length === maxFileCount });
            }
            return child;
        });

        const finalChildren = maxFileCount === undefined ? rest.children : childrenWithProps;

        return (
            <Fragment>
                <UploadOss
                    dragAble={false}
                    ref={ref}
                    listType={isSingle ? 'picture-card' : 'text'}
                    uploadUrl="/api/resource/public/oss/producePutPreSignUrls"
                    checkFileSize={checkFileSize}
                    onPreview={isSingle && handleImgPreview}
                    checkFileType={checkFileType}
                    sysCode="OA"
                    businessCode="SysRule"
                    categoryCode={categoryCode}
                    fileList={allFileList || []}
                    uploadResource={value && value.uploadResourceFile}
                    setFileList={changeAllFileList}
                    checkFileTypeMsg={checkFileTypeMsg}
                    checkFileSizeMsg={checkFileSizeMsg}
                    {...rest}
                >
                    {rest.children ? finalChildren : fetchSingle(isSingle)}
                    {/* {rest.children ? (
                        rest.children
                    ) : isSingle ? (
                        allFileList.length >= 1 ? null : (
                            uploadButton
                        )
                    ) : (
                        <Button type="primary" ghost>
                            <Icon type="upload" />
                            上传文件
                        </Button>
                    )} */}
                </UploadOss>
                <Modal visible={previewVisible} footer={null} onCancel={() => setPreviewVisible(false)}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </Fragment>
        );
    }
);

export default FileUpload;
